#
# Find all the possible char values for each element of a file
#

# to xor ascii and back into hex: hex(int('0x61',16) ^ int('0x63',16))
# to xor char values and back into hex: hex(int(ord('a'))^int(ord('c')))
#
# The pairs appear to be 1-4, 2-6, 3-5... 
#

import os,sys
import string
import itertools

if len(sys.argv) != 2:
    print "USAGE: find_ascii_pairs.py <file>"
    sys.exit(1)

values = list(string.ascii_letters) # add any possible characters here
values.extend([' ','.',','])

# Adding these in didn't reduce the unmatched characters! Could still be there 
#   I guess?
#values.extend(string.digits)
#values.extend(['!',';',':'])
#values.extend(['\n'])

# Some more stuff to try
#values.extend(string.digits)
#values.extend(string.punctuation)

#This should be literally all possible values
#values = list(string.printable)

# There are 52 values here, this means N!/(R!(N-R)!) = 52!/100! = 1326 combos
# But since there are overlap in xor'ed values, this is a dict of lists
combs = {}
for i in itertools.combinations(values,2):
    v = int(ord(i[0])) ^ int(ord(i[1]))
    #print i[0] + " XOR " + i[1] + " = " + str(v)
    if not combs.has_key(v):
        combs[v] = [(i[0],i[1])]
    else:
        combs[v].append( (i[0],i[1]) )


possibilities = []
no_value_count = 0

f=bytearray(open(sys.argv[1],'rb').read())
for i in range(len(f)):
    v = f[i]
    a = []
    if combs.has_key(v):
        a = combs[v]
    else:
        no_value_count = no_value_count + 1

    print hex(v) + " = " + str(a)

    possibilities.append(a)


print "There are " + str(i) + " characters in the file"
print "Couldn't find a value for " + str(no_value_count) + " items"
